﻿using System;
using System.Collections.Generic;
using System.Windows.Media;
using System.Windows.Media.Media3D;

namespace ComplexAlloysVisualisation
{
    public class AtomBuldier
    {
        public Model3DGroup CreateModel(IEnumerable<Atom> atoms, double opacity)
        {
            Model3DGroup atomsCollecion = new Model3DGroup();
            var sphere = Sphere3D.GetSphere();

            foreach (var atom in atoms)
            {
                var color = new Color();
                color.ScR = (float)atom.AluminiumProbability;
                //color.ScG = (float)(-2 * Math.Abs(atom.MagnesiumProbability - 0.5f) + 1.0f); // function has maximum for 0.5 prob
                // x=|PMg-PAl|/|PMg+PAl| where I(G)=1-x
                color.ScG = 1.0f - (float)(Math.Abs(atom.MagnesiumProbability - atom.AluminiumProbability) / Math.Abs(atom.MagnesiumProbability + atom.AluminiumProbability));
                color.ScB = (float)atom.MagnesiumProbability;
                var alpha = (float)(1.0 - atom.VacancyProbability);
                color.ScA = alpha;
                Material material;
                var brush = new SolidColorBrush(color);
                brush.Opacity = opacity;
                //if (alpha < 0.3f)
                //{
                //    material = new EmissiveMaterial(brush);   // to mark vacancy as a half transparent gray atom, issues with z-buffer and diffuse material
                //}
                //else
                //{
                //    material = new DiffuseMaterial(brush);
                //}
                //brush.Opacity = alpha;
                material = new DiffuseMaterial(brush);
                var ball = new GeometryModel3D(sphere, material);
                var x = atom.X * Atom.ToAngstrom;
                var y = atom.Y * Atom.ToAngstrom;
                var z = atom.Z * Atom.ToAngstrom;
                var translate = new TranslateTransform3D(x, y, z);
                var scale = new ScaleTransform3D(1.0, 1.0, 1.0, x, y, z);
                var groupTrans = new Transform3DGroup();
                groupTrans.Children.Add(translate);
                groupTrans.Children.Add(scale);
                ball.Transform = groupTrans;
                atomsCollecion.Children.Add(ball);
            }
            return atomsCollecion;
        }
    }
}